package com.exchange.controller.app.kyc;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.aliyun.oss.OSSClient;
import com.exchange.common.model.User;
import com.exchange.common.model.UserKyc;
import com.exchange.interceptor.EnumError;
import com.exchange.util.aliOSSFileUtil;
import com.jfinal.aop.Before;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.upload.UploadFile;

public class KycService {
	
	private Cache rides = Redis.use(PropKit.get("redisName"));
	
	@Before(Tx.class)
    public Ret authC1(User user, String lastname, String firstname, String country, String idtype, String idno, String city) {  	
    	int verified = user.getVerified();
    	if(verified == 0 || verified == 2) {//未提交或者审核不通过
    		UserKyc userKyc = new UserKyc()
			.setCreateTime(new Date())
			.setUserId(user.getId())
			.setLastName(lastname)
			.setFirstName(firstname)
			.setCountry(country)
			.setCity(city)
			.setIdType(idtype)
			.setIdNo(idno)
			.setState(3);//因为不进行c1审核,所以这里直接3
    		userKyc.save();
    		user.setVerified(3);//因为不进行c1审核,所以这里直接3
    		user.update();
    		rides.set(user.getAccount(), user);
    		
    		return Ret.ok("userKyc",userKyc).set("userVerified", 3);
    	}
    	return Ret.fail("msg", EnumError.C1_V_FAIL.getCode());
    }
	
	@Before(Tx.class)
	public Ret authC2(User user, List<UploadFile> ufs) {
		Map<String,String> urls = new HashMap<String,String>();

    	if(user.getVerified() == 3 || user.getVerified() == 5) {
    		for(UploadFile uf : ufs) {
    			OSSClient ossClient = aliOSSFileUtil.getOSSClient();
    	        String picUrl = aliOSSFileUtil.uploadImg(ossClient, uf.getFile(), PropKit.get("bucketApp"));
    	        urls.put(uf.getParameterName(),picUrl);
            }
    		//获取kyc
    		UserKyc userKyc = UserKyc.dao.findFirst("SELECT * FROM t_user_kyc WHERE userId = ?",user.getId());
			userKyc.setPicBack(urls.get("picback"));
			userKyc.setPicFace(urls.get("picface"));
			userKyc.setPicHold(urls.get("picback"));
			userKyc.update();
        	user.setVerified(4);
        	user.update();
        	rides.set(user.getAccount(), user);
        	
        	return Ret.ok("userKyc",userKyc).set("userVerified", 4);
    	}
    	return Ret.fail("msg", EnumError.C2_V_FAIL.getCode());
	}
	
	public Ret getKycStep(User user){
		UserKyc userKyc = UserKyc.dao.findFirst("SELECT * FROM t_user_kyc WHERE userId = ?",user.getId());		
		return Ret.ok("userKyc",userKyc);
    }
	
}
